using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace Phoenix.Commands
{
    public class InvokeCommand
    {
        #region public static ICommand UIElement.OnItemSelected
        public static readonly DependencyProperty OnItemSelectedProperty = 
            DependencyProperty.RegisterAttached("OnItemSelected", typeof (ICommand), typeof (InvokeCommand), new PropertyMetadata(OnItemSelectedChanged));

        public static ICommand GetOnItemSelected(UIElement element)
        {
            return (ICommand) element.GetValue(OnItemSelectedProperty);
        }

        public static void SetOnItemSelected(UIElement element, ICommand value)
        {
            element.SetValue(OnItemSelectedProperty, value);
        }
        #endregion

        static void OnItemSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var selector = d as Selector;
            if (selector == null) return;

            selector.SelectionChanged += SelectorSelectionChanged;
        }

        static void SelectorSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selector = (Selector)sender;
            var command = GetOnItemSelected(selector);
            if (command == null)
                return;

            var selectedItem = selector.SelectedItem;
            if (selectedItem is ListBoxItem)
                selectedItem = null;
            command.Execute(selectedItem);
        }
    }
}